package com.atguigu.dga.ds.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.dga.ds.bean.TDsTaskDefinition;
import com.atguigu.dga.ds.mapper.TDsTaskDefinitionMapper;
import com.atguigu.dga.ds.service.TDsTaskDefinitionService;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuzhida
 * @since 2024-06-30
 */
@Service
@DS("dolphinscheduler")
public class TDsTaskDefinitionServiceImpl extends ServiceImpl<TDsTaskDefinitionMapper, TDsTaskDefinition> implements TDsTaskDefinitionService {

    /**
     * 获取任务实例
     * @param assessDate
     * @return
     */
    @Override
    public List<TDsTaskDefinition> getTDsTaskDefinitionList(String assessDate) {
        List<TDsTaskDefinition> tDsTaskDefinitionList = list(
                new QueryWrapper<TDsTaskDefinition>()
                        .eq("task_type", "SHELL")
        );

        extractSql(tDsTaskDefinitionList);
        
        return tDsTaskDefinitionList;
    }

    /**
     * 提取sql
     * @param tDsTaskDefinitionList
     */
    private void extractSql(List<TDsTaskDefinition> tDsTaskDefinitionList) {
        for (TDsTaskDefinition tDsTaskDefinition : tDsTaskDefinitionList) {
            String taskParams = tDsTaskDefinition.getTaskParams();
            JSONObject jsonObject = JSONObject.parseObject(taskParams);
            String taskSql = jsonObject.getString("rawScript");

            //开始位置
            // 先找with， 如果有， 则使用，如果没有，则找insert
            int startIndex ;
            int withIndex = taskSql.indexOf("with");
            int insertIndex = taskSql.indexOf("insert");
            if (withIndex != -1){
                startIndex = withIndex;
            } else {
                startIndex = insertIndex;
            }
            
            if (startIndex == -1){
                continue;
            }
            
            //结束位置
            // 从开始位置往后先找 ; ， 如果有，则使用， 如果没有， 找 "
            int endIndex;
            int fenHaoIndex = taskSql.indexOf(";", startIndex);
            int yinHaoIndex = taskSql.indexOf("\"", startIndex);
            if (fenHaoIndex != -1){
                endIndex = fenHaoIndex;
            } else {
                endIndex = yinHaoIndex;
            }
            
            //截取SQ
            String sql = taskSql.substring(startIndex, endIndex);
            tDsTaskDefinition.setTaskSql(sql);
        }
    }
}
